class Modal {
    constructor() {
        this.modal = document.getElementById('custom-modal');
        this.titleEl = document.getElementById('modal-title');
        this.messageEl = document.getElementById('modal-message');
        this.closeBtn = document.getElementById('modal-close');
        
        this.closeBtn.addEventListener('click', () => this.hide());
    }

    show(message, title = '提示') {
        this.titleEl.textContent = title;
        this.messageEl.textContent = message;
        this.modal.classList.remove('hidden');
    }

    hide() {
        this.modal.classList.add('hidden');
    }
}

class LotteryWheel {
    constructor() {
        this.canvas = document.getElementById('wheel');
        this.ctx = this.canvas.getContext('2d');
        this.adjustCanvasSize();
        this.prizes = [];
        this.isSpinning = false;
        this.currentRotation = 0;
        this.modal = new Modal();
        this.winningIndex = null;
        this.init();
    }

    adjustCanvasSize() {
        // 根据容器大小调整canvas尺寸
        const container = this.canvas.parentElement;
        const size = Math.min(container.clientWidth, container.clientHeight);
        this.canvas.width = size;
        this.canvas.height = size;
    }

    init() {
        // 获取奖品数据
        this.fetchPrizes();
        
        // 添加窗口大小改变事件监听
        window.addEventListener('resize', () => {
            this.adjustCanvasSize();
            this.drawWheel();
        });

        // 绑定抽奖按钮事件
        document.getElementById('spin-button').addEventListener('click', () => {
            if (!this.isSpinning) {
                this.spin();
            }
        });
    }

    async fetchPrizes() {
        try {
            const response = await fetch('api/get_prizes.php');
            this.prizes = await response.json();
            // 打印获取到的奖品列表
            console.log('Fetched Prizes:', this.prizes);
            this.drawWheel();
        } catch (error) {
            console.error('获取奖品失败:', error);
        }
    }

    drawWheel() {
        console.log('Drawing wheel with prizes:', this.prizes);
        
        const centerX = this.canvas.width / 2;
        const centerY = this.canvas.height / 2;
        const radius = Math.min(centerX, centerY) - (this.canvas.width < 400 ? 5 : 10);
        const segments = this.prizes.length;
        const arc = (Math.PI * 2) / segments;
        const fontSize = Math.max(12, Math.floor(this.canvas.width / 25));

        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

        // 从12点钟方向开始绘制
        const startOffset = -Math.PI / 2;

        for (let i = 0; i < segments; i++) {
            console.log(`Drawing segment ${i}:`, this.prizes[i].name);
            
            this.ctx.beginPath();
            const isWinningSegment = this.winningIndex === i;
            this.ctx.fillStyle = isWinningSegment 
                ? '#FFD700'
                : (i % 2 ? '#FFB6C1' : '#FFA07A');
            
            const startAngle = startOffset + (i * arc);
            const endAngle = startAngle + arc;
            
            this.ctx.moveTo(centerX, centerY);
            this.ctx.arc(centerX, centerY, radius, startAngle, endAngle);
            this.ctx.closePath();
            this.ctx.fill();

            // 为中奖项添加发光效果
            if (isWinningSegment) {
                this.ctx.save();
                this.ctx.shadowColor = '#FFD700';
                this.ctx.shadowBlur = 20;
                this.ctx.stroke();
                this.ctx.restore();
            }

            // 绘制文字
            this.ctx.save();
            this.ctx.translate(centerX, centerY);
            this.ctx.rotate(startAngle + arc / 2);
            this.ctx.textAlign = 'center';
            this.ctx.fillStyle = isWinningSegment ? '#FF0000' : '#000';
            this.ctx.font = `${isWinningSegment ? 'bold' : 'normal'} ${fontSize}px Microsoft YaHei`;
            const textDistance = radius * 0.75;
            this.ctx.fillText(this.prizes[i].name, textDistance, 0);
            this.ctx.restore();
        }

        // 绘制中心点
        this.ctx.beginPath();
        this.ctx.fillStyle = '#FF4500';
        const centerPointRadius = this.canvas.width <= 300 ? 10 : 15;
        this.ctx.arc(centerX, centerY, centerPointRadius, 0, Math.PI * 2);
        this.ctx.fill();
    }

    async spin() {
        if (this.isSpinning) return;
        
        this.isSpinning = true;
        const button = document.getElementById('spin-button');
        button.disabled = true;

        try {
            const response = await fetch('api/draw.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'same-origin'
            });
            
            const result = await response.json();
            
            if (result.success) {
                // 根据奖品ID找到对应的索引
                // const prizeIndex = this.prizes.findIndex(p => p.id === parseInt(result.prize.id));
                const prizeIndex = result.prizeIndex;
                if (prizeIndex === -1) {
                    console.error('Invalid prize index:', result);
                    this.modal.show('系统错误，请稍后重试');
                    button.disabled = false;
                    this.isSpinning = false;
                    return;
                }
                
                const targetRotation = this.calculateTargetRotation(prizeIndex);
                this.animateWheel(targetRotation, result);
            } else {
                this.modal.show(result.message, '提示');
                button.disabled = false;
                this.isSpinning = false;
            }
        } catch (error) {
            console.error('抽奖失败:', error);
            this.modal.show('系统错误，请稍后重试');
            button.disabled = false;
            this.isSpinning = false;
        }
    }

    calculateTargetRotation(prizeIndex) {
        const segments = this.prizes.length;
        const segmentAngle = 360 / segments;
        
        // 添加调试日志
        console.log('Calculate rotation:', {
            prizeIndex,
            segments,
            segmentAngle,
            prize: this.prizes[prizeIndex]
        });
        
        // 计算目标角度（从12点钟方向逆时针计算，确保指针指向奖品中心）
        const targetAngle = 360 - (prizeIndex * segmentAngle);
        // 添加偏移以指向奖品中心
        const offsetAngle = segmentAngle / 2;
        
        // 计算最终角度：基础圈数 + 目标角度 + 偏移
        const finalAngle = (targetAngle - offsetAngle + 360) % 360;
        const baseRotations = 5 * 360; // 5圈完整旋转
        
        // 记录最终角度
        console.log('Final rotation:', {
            targetAngle,
            offsetAngle,
            finalAngle,
            totalRotation: baseRotations + finalAngle
        });
        
        return baseRotations + finalAngle;
    }

    animateWheel(targetRotation, result) {
        // 使用实际的奖品ID查找索引
        this.winningIndex = this.prizes.findIndex(p => p.id === parseInt(result.prize.id));
        const duration = 4000;
        const startTime = performance.now();
        
        // 使用当前角度作为起始角度
        const startAngle = this.currentRotation % 360;
        
        const animate = (currentTime) => {
            const elapsed = currentTime - startTime;
            const progress = Math.min(elapsed / duration, 1);
            
            // 使用缓动函数使动画更自然
            const easeOut = (t) => {
                return 1 - Math.pow(1 - t, 5);
            };
            
            // 计算当前进度
            const currentProgress = easeOut(progress);
            
            // 计算当前角度
            const deltaRotation = targetRotation - startAngle;
            this.currentRotation = startAngle + (deltaRotation * currentProgress);
            
            // 绘制转盘
            this.ctx.save();
            this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2);
            this.ctx.rotate((this.currentRotation * Math.PI) / 180);
            this.ctx.translate(-this.canvas.width / 2, -this.canvas.height / 2);
            this.drawWheel();
            this.ctx.restore();
            
            if (progress < 1) {
                requestAnimationFrame(animate);
            } else {
                // 确保最终角度正确
                this.currentRotation = targetRotation;
                this.isSpinning = false;
                document.getElementById('spin-button').disabled = false;
                this.showWinnerForm(result);
            }
        };
        
        requestAnimationFrame(animate);
    }

    showWinnerForm(result) {
        if (result.prize) {
            // 打印调试信息
            console.log('Prize Result:', result);
            
            if (result.prize.name === '谢谢参与') {
                this.modal.show('很遗憾，未中奖，祝您新春快乐！', '抽奖结果');
                return;
            }
            
            const form = document.getElementById('winner-form');
            form.classList.remove('hidden');
            
            const recipientForm = document.getElementById('recipient-form');
            const newForm = recipientForm.cloneNode(true);
            recipientForm.parentNode.replaceChild(newForm, recipientForm);
            
            newForm.addEventListener('submit', async (e) => {
                e.preventDefault();
                await this.submitWinnerInfo(result.prize.id);
            });
        }
    }

    async submitWinnerInfo(prizeId) {
        const form = document.getElementById('recipient-form');
        const formData = new FormData(form);
        formData.append('prize_id', prizeId);

        try {
            const response = await fetch('api/submit_winner.php', {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const result = await response.json();
            
            if (result.success) {
                this.modal.show('信息提交成功！我们会尽快为您发放奖品。', '提交成功');
                form.reset();
                document.getElementById('winner-form').classList.add('hidden');
            } else {
                this.modal.show(result.message, '提交失败');
            }
        } catch (error) {
            console.error('提交信息失败:', error);
            this.modal.show('提交信息失败，请稍后重试。', '系统错误');
        }
    }
}

// 初始化抽奖转盘
document.addEventListener('DOMContentLoaded', () => {
    new LotteryWheel();
});

// 在中奖后显示表单时，添加prize_id到表单
function showWinnerForm(prizeId) {
    const form = document.getElementById('recipient-form');
    // 添加隐藏的prize_id字段
    let prizeIdInput = form.querySelector('input[name="prize_id"]');
    if (!prizeIdInput) {
        prizeIdInput = document.createElement('input');
        prizeIdInput.type = 'hidden';
        prizeIdInput.name = 'prize_id';
        form.appendChild(prizeIdInput);
    }
    prizeIdInput.value = prizeId;
    
    document.getElementById('winner-form').classList.remove('hidden');
}

// 处理表单提交
document.getElementById('recipient-form').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    fetch('/api/submit_winner.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showModal('提交成功', '您的中奖信息已提交，我们会尽快为您发货！');
            document.getElementById('winner-form').classList.add('hidden');
        } else {
            showModal('提交失败', data.message || '请稍后重试');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showModal('错误', '系统错误，请稍后重试');
    });
}); 